package com.zyp.weibo_demo.controller;

import com.zyp.weibo_demo.mapper.UserMapper;
import com.zyp.weibo_demo.pojo.dto.UserRegDto;
import com.zyp.weibo_demo.pojo.entity.User;
import com.zyp.weibo_demo.pojo.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDto userRegDto) {
        UserVo u = mapper.selectByUsername(userRegDto.getUsername());
        if (u != null) {
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDto,user);
        mapper.insert(user);
        return 1;
    }

    @RequestMapping("/login")
    public int login(@RequestBody UserRegDto userRegDto, HttpSession session) {
        UserVo u = mapper.selectByUsername(userRegDto.getUsername());
        if (u!=null) {
            if (u.getPassword().equals(userRegDto.getPassword())) {
                session.setAttribute("user",u);
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @RequestMapping("/currentUser")
    public UserVo currentUser(HttpSession session) {
        return (UserVo) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        session.removeAttribute("user");
    }
}
